<template>
  <div class="header-nav">
    <div class="header-nav-content">
      <mx-link to="/">
        <icon class="logo mr-16 cursor-pointer" name="ic_logo" />
      </mx-link>

      <div v-if="!isSearchPage" class="flex">
        <div ref="nav" class="nav">
          <div
            v-for="(item, index) in prevNavList"
            :key="index"
            class="nav-item cursor-pointer"
            :class="{ active: currentChannelIndex == item.id }"
            @click="jumpPage(item, false)"
          >
            {{ $t(item.name) }}
          </div>
        </div>
        <div
          v-if="nextNavList.length > 0"
          class="more click"
          @click="showChannel"
        >
          <icon
            size="24px"
            :name="isSelectedNext ? 'ic_more_red' : 'ic_more'"
          />
        </div>

        <div class="search-icon click" @click="showSearch">
          <icon
            class="search cursor-pointer ml-4"
            size="24px"
            name="ic_search_black"
          />
        </div>
      </div>

      <!-- 搜索页面的搜索框 -->
      <div v-if="isSearchPage" class="flex">
        <div class="search-box">
          <icon name="ic_search_grey" class="mr-8" size="20px" />
          <input
            v-model="query"
            class="search-box-input"
            name="q"
            :placeholder="$t('search_keyword')"
            @keyup.enter.stop="search"
          />
          <icon
            v-if="query"
            name="ic_close_grey"
            class="search-box-clear ml-16 cursor-pointer"
            size="20px"
            @click.native.stop="query = ''"
          />
        </div>
        <div class="search-btn ml-16 cursor-pointer" @click="search">
          {{ $t('search') }}
        </div>
      </div>

      <mx-link
        :to="MEDIA_URL"
        :with-locale="false"
        target="_blank"
        class="ml-auto"
      >
        <div class="release cursor-pointer click mr-4">
          <icon size="20px" name="ic_release" />
          <p class="ml-6 cursor-pointer">{{ $t('publish_works') }}</p>
        </div>
      </mx-link>

      <language-select />
    </div>

    <div v-if="showObj.channel" ref="channel" class="more-channel">
      <div class="more-channel-content">
        <div class="more-channel-content-box">
          <div
            v-for="(item, index) in nextNavList"
            :key="index"
            class="more-channel-item cursor-pointer"
            :class="{ active: currentChannelIndex == item.id }"
            @click="jumpPage(item, true)"
          >
            {{ item.name }}
          </div>
        </div>

        <icon
          size="24px"
          class="ml-auto cursor-pointer"
          name="ic_close_black"
          @click="showObj.channel = false"
        />
      </div>
    </div>

    <!-- 其他页面的搜索框 点击搜索再跳转到搜索页面 -->
    <div v-if="showObj.search" ref="search" class="more-channel">
      <div class="more-channel-content">
        <div class="flex">
          <div class="search-box w-916">
            <icon name="ic_search_grey" class="mr-8" size="20px" />
            <input
              v-model="queryFilter"
              class="search-box-input"
              name="q"
              :placeholder="$t('search_keyword')"
              @keyup.enter.stop="beforeSearch"
            />
            <icon
              v-if="queryFilter"
              name="ic_close_grey"
              class="search-box-clear ml-16"
              size="20px"
              @click.native.stop="queryFilter = ''"
            />
          </div>
          <div class="search-btn ml-16 cursor-pointer" @click="beforeSearch">
            {{ $t('search') }}
          </div>
        </div>
        <icon
          size="24px"
          class="ml-auto"
          name="ic_close_black"
          @click="showObj.search = false"
        />
      </div>
    </div>
  </div>
</template>

<script>
import Icon from './Icon.vue';
import LanguageSelect from './LanguageSelect.vue';
import { cloneDeep } from 'lodash';
import { LANGUAGE } from '@/constants/index';
import MxLink from './MxLink.vue';

const KM_DEFAULT_CHANNEL = [
  {
    name: 'home_page',
    id: 'home'
  },
];
const ZH_DEFAULT_CHANNEL = [
  {
    name: 'home_page',
    id: 'home'
  },
  {
    name: 'focus_news',
    id: 84
  },
  {
    name: '特色出品',
    id: 'topic'
  }
];
const MAX_NAV_WIDTH = 546;
const MEDIA_URL = process.env.MEDIA_URL;

export default {
  components: { Icon, LanguageSelect, MxLink },

  data() {
    return {
      MEDIA_URL,
      showObj: {
        channel: false,
        search: false
      },
      query: '',
      queryFilter: '',
      currentChannelIndex: 'home',
      prevNavList: [],
      nextNavList: [],
      allNavList: []
    };
  },

  computed: {
    language() {
      return this.$store.state.app.language;
    },
    isSearchPage() {
      return this.$route.path.includes('search');
    },
    isSelectedNext() {
      return this.nextNavList.some(item => item.id == this.currentChannelIndex);
    }
  },

  watch: {
    language() {
      this.getNav();
    },
    '$route.path': {
      handler: 'getCurrentPage',
      deep: true,
      immediate: true
    }
  },

  created() {
    this.getNav();
  },

  mounted() {
    document.addEventListener('click', this.registerListener, true);
  },

  beforeDestroy() {
    this.removeListener();
  },

  methods: {
    registerListener(e) {
      if (this.$refs.channel && !this.$refs.channel.contains(e.target)) {
        this.showObj.channel = false;
      }
      if (this.$refs.search && !this.$refs.search.contains(e.target)) {
        this.showObj.search = false;
      }
    },

    removeListener() {
      document.removeEventListener('click', this.registerListener);
    },

    getCurrentPage() {
      const { path } = this.$route;
      if (path.includes('channel')) {
        this.currentChannelIndex = path.split('/').reverse()[0];
      } else if (path.includes('topic-list')) {
        this.currentChannelIndex = 'topic';
      } else if (path === '/zh' || path === '/km') {
        this.currentChannelIndex = 'home';
      } else if (path.includes('/topic/')) {
        this.currentChannelIndex = this.findTopicIdByPath(path);
      } else {
        this.currentChannelIndex = -1;
      }
    },

    findTopicIdByPath(path) {
      const subjectId = path.split('/').reverse()[0];
      const item = this.allNavList.filter(
        item => item.subjectId == subjectId
      )[0];
      return item ? item.id : -1;
    },

    async getNav() {
      const channelList = await this.$API.articleGetChannel();
      const { language } = this;
      const list =
        language === LANGUAGE.ZH
          ? [...ZH_DEFAULT_CHANNEL, ...channelList]
          : [...KM_DEFAULT_CHANNEL, ...channelList];
      this.allNavList = cloneDeep(list);
      this.prevNavList = cloneDeep(list);
      this.nextNavList = [];
      this.$nextTick(() => {
        this.calculateNav();
      });
    },

    calculateNav() {
      if (!this.$refs.nav || this.isSearchPage) return;
      const width = Math.ceil(this.$refs.nav.getBoundingClientRect().width);
      const isBeyond = width >= MAX_NAV_WIDTH;
      if (isBeyond) {
        this.prevNavList = this.allNavList.slice(0, 5);
        this.nextNavList = this.allNavList.slice(5);
      }
    },

    showSearch() {
      this.showObj = {
        channel: false,
        search: true
      };
      this.queryFilter = '';
    },

    showChannel() {
      this.showObj = {
        channel: true,
        search: false
      };
    },

    jumpPage({ id, name, subjectId, channelType }) {
      this.currentChannelIndex = id;
      this.showObj.channel = false;

      switch (id) {
        case 'home':
          this.$router.push({
            path: this.localePath('/', this.$i18n.locale)
          });

          break;
        case 'topic':
          this.$router.push({
            path: this.localePath('/m/topic-list', this.$i18n.locale)
          });
          break;
        default:
          // 专题频道
          if (channelType === 1 && subjectId) {
            this.$router.push({
              path: this.localePath(`/m/topic/${subjectId}`, this.$i18n.locale)
            });
            return;
          }
          this.$router.push({
            path: this.localePath(`/m/channel/${id}`, this.$i18n.locale)
          });
          break;
      }
    },

    beforeSearch() {
      const { queryFilter } = this;
      if (!queryFilter || queryFilter.trim() === '') return;
      this.showObj.search = false;
      this.$store.commit('app/updateSearchContent', queryFilter);
      this.query = queryFilter;
      this.$router.push({
        path: this.localePath('/m/search', this.$i18n.locale)
      });
    },

    search() {
      const { query } = this;
      if (!query || query.trim === '') return;
      const { searchContent } = this.$store.state.app;
      if (query === searchContent) return;

      this.$store.commit('app/updateSearchContent', query);
    }
  }
};
</script>

<style lang="scss" scoped>
@import '~assets/styles/variable.scss';

.header-nav {
  width: 100%;
  height: $page-nav-height;
  background: #fff;
  box-shadow: 0 1px 0 0 rgba(12, 12, 28, 0.06);
  position: fixed;
  z-index: 9999;
}

.more-channel {
  position: absolute;
  top: 64px;
  left: 0;
  right: 0;
  width: 100%;
  background: #ffffff;
  box-shadow: 0 1px 0 0 rgba(12, 12, 28, 0.06);
  z-index: 9999;

  .more-channel-content {
    padding: 0 16px;
    width: $page-width;
    min-height: 72px;
    margin: 0 auto;
    display: flex;
    align-items: center;
  }

  .more-channel-content-box {
    width: 992px;
    display: flex;
    flex-wrap: wrap;
  }

  .more-channel-item {
    border-radius: 8px;
    padding: 0 12px;
    height: 32px;
    font-size: 14px;
    color: rgba(12, 12, 28, 0.7);
    line-height: 32px;
    background: rgba(12, 12, 28, 0);
    border-radius: 8px;
  }

  .active {
    background: #fa4646;
    color: #ffffff;
  }
}

.header-nav-content {
  width: $page-width;
  height: $page-nav-height;
  margin: 0 auto;
  padding: 12px 16px;
  display: flex;
  height: 64px;
  align-items: center;
  position: relative;

  .logo {
    width: 78px;
    height: 28px;
  }

  .nav {
    display: flex;
    align-items: center;

    .nav-item {
      font-size: 16px;
      color: rgba(12, 12, 28, 0.7);
      letter-spacing: 0;
      text-align: center;
      padding: 0 8px;
      margin-right: 4px;
    }

    .active {
      color: #fd4b49;
    }
  }

  .more {
    height: 40px;
    padding: 8px;
  }

  .release {
    display: flex;
    padding: 0 12px;
    height: 32px;
    align-items: center;
    font-size: 14px;
    color: #0c0c1c;
  }
}

.search-icon {
  height: 40px;
  padding: 8px;
}

.search-box {
  width: 525px;
  height: 40px;
  position: relative;
  background: #ffffff;
  border: 0.5px solid #ccc;
  border-radius: 8px;
  padding: 10px 16px;
  display: flex;
  align-items: center;
}

.w-916 {
  width: 916px;
}

.search-box-input {
  flex: 1;
  font-size: 14px;
  color: #0c0c1c;
  outline: none;
  border: 0;
}

.search-box:hover {
  border: 0.5px solid #fa4646;
}
.search-box:active {
  border: 0.5px solid #fa4646;
}
.search-box:focus {
  border: 0.5px solid #fa4646;
}

.search-btn {
  height: 40px;
  line-height: 40px;
  background: #fa4646;
  border-radius: 20px;
  padding: 0 16px;
  font-size: 14px;
  color: #ffffff;
}
</style>
